package com.ivan.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MessageContainer<syncronized> {
	
	private  List<Message> messages = null;

	@SuppressWarnings("rawtypes")
	private static MessageContainer container;
	
	private MessageContainer(){
		this.init();
	}
	
	public void refreshMessag(String name, String content){
		System.out.println("Before add message...:" + this.messages.size());
		Message message = new Message();
		message.setName(name);
		message.setContent(content);
		message.setDateTime(DateUtil.now());
		this.messages.add(message);
		System.out.println("After add message...:" + this.messages.size());
	}
	
	private void init() {
		this.messages = Collections.synchronizedList(new ArrayList<Message>());
	}
	
	/**
	 * Return the String message to end point.
	 * @param pos
	 * @return
	 */
	public synchronized MessageUnit getMessage(int pos){
		MessageUnit unit = new MessageUnit();
		unit.setPos(this.messages.size());
		StringBuffer sb = new StringBuffer();
		System.out.println("Message size: " + messages.size() + ", Pos: " + pos);
		if(messages.size() > pos){
			sb.append("\r\n");
		}
		for(int i = pos; i <= (messages.size() - 1); i++){
			Message message = this.messages.get(i);
			sb.append(message.getDateTime() + "\r\n")
				.append(message.getName() + " : " + message.getContent());
		}
		unit.setContent(sb.toString());
		return unit;
	}

	@SuppressWarnings("rawtypes")
	public static MessageContainer getInstance(){
		if(container == null){
			container = new MessageContainer();
		}
		return container;
	}
	
	
	
	public static void main(String[] args) {
		
	}

}
